package mover;

import java.awt.*;
import java.awt.geom.Point2D;

import extensible.Canvas;

import utilities.Force;

/**
 * 
 * @author Dr. Duvall
 * @edited Ga-Young Joung
 *
 */
public class Spring extends Image
{
	
    private Mass myStart;
    private Mass myEnd;
    private double myOriginalLength;
    private double myOriginalK;


    /**
     * constructs a spring between two given masses
     * @param start - mass
     * @param end - mass
     * @param length - length of spring
     * @param kVal - k value of the spring
     */
    public Spring (Mass start, Mass end, double length, double kVal)
    {
        super(start.getCenter(), new Dimension(), new Point2D.Double(), "images/spring.gif", 0);
        myStart = start;
        myEnd = end;
        myOriginalLength = length;
        myOriginalK = kVal;
    }

    /**
     * updates the center, size, and angle of the spring image
     */
    public void update (Canvas canvas)
    {
    	double currentK = SpringAndMassParameters.kValScale*myOriginalK;
    	double currentLength = SpringAndMassParameters.lengthScale*myOriginalLength;
        Point2D.Double start = myStart.getCenter();
        Point2D.Double end = myEnd.getCenter();  
        int dx = (int) (start.x - end.x);
        int dy = (int) (start.y - end.y);

        // apply hooke's law to each attached mass
        Force f = new Force(Force.angleBetween(dx, dy),
                            currentK * (currentLength - Force.distanceBetween(dx, dy)));
        myStart.applyForce(f);
        myEnd.applyForce(f.negate());

        // update spring values based on attached masses
        setCenter((int) ((start.x + end.x) / 2), (int) ((start.y + end.y) / 2));
        setSize((int)start.distance(end), 20);
        setAngle(Force.angleBetween(dx, dy));
    }
    
    /**
     * returns string description of the object Spring
     */
    public String toString() {
    	return "Spring: "+myStart+","+myEnd+","+myOriginalLength+","+myOriginalK;
    }
}
